import requests
import json
from setenv import setLotteryDir
from setenv import getFileDir
from setenv import getFileName



def fetch_lotto_numbers(url):
    response = requests.get(url)
    setLotteryDir()
    dltdir = getFileDir()
    dltfilename = getFileName("dltfilename")
    if response.status_code == 200:
        html = response.text
        # print(html)
        # 假设中奖号码在HTML中的某个特定标签内，例如：<div class="lotto-numbers">
        data = json.loads(str(html))
        # print(data)
        # print(data.get('value').get('lastPoolDraw').get('lotteryDrawNum'))
        # print(data.get('value').get('lastPoolDraw').get('lotteryDrawResult'))
        # print(data.get('value').get('lastPoolDraw').get('lotteryDrawTime'))
        # print(data.get('value').get('lastPoolDraw').get('lotteryGameName'))
        # print(data.get('value').get('lastPoolDraw').get('lotteryGameNum'))
        # lotteryDrawNum = data.get('value').get('lastPoolDraw').get('lotteryDrawNum')
        # lotteryDrawResult = data.get('value').get('lastPoolDraw').get('lotteryDrawResult')
        # lotteryDrawTime = data.get('value').get('lastPoolDraw').get('lotteryDrawTime')
        # lotteryGameName = data.get('value').get('lastPoolDraw').get('lotteryGameName')
        # lotteryGameNum = data.get('value').get('lastPoolDraw').get('lotteryGameNum')
        # print(data.get('value').get('list')[0].get('lotteryDrawNum'))
        # print(data.get('value').get('list')[0].get('lotteryDrawResult'))
        # print(data.get('value').get('list')[0].get('lotteryDrawTime'))
        # print(data.get('value').get('list')[0].get('lotteryGameName'))
        # print(data.get('value').get('list')[0].get('lotteryGameNum'))
        lotteryDrawNum = data.get('value').get('list')[0].get('lotteryDrawNum')
        lotteryDrawResult = data.get('value').get('list')[0].get('lotteryDrawResult')
        lotteryDrawTime = data.get('value').get('list')[0].get('lotteryDrawTime')
        lotteryGameName = data.get('value').get('list')[0].get('lotteryGameName')
        lotteryGameNum = data.get('value').get('list')[0].get('lotteryGameNum')


        # 使用上下文管理器打开文件
        with open( str(dltdir) + "/" + str(dltfilename) , "w") as file:
        # 写入数据
            file.write(str(lotteryDrawResult) + "\n")

        file.close
        print(lotteryGameName,"开奖期号：", lotteryDrawNum)
        print(lotteryGameName,"开奖时间：", lotteryDrawTime)
        print(lotteryGameName,"开奖号码：", lotteryDrawResult)

        return lotteryDrawResult
    return None

if __name__ == '__main__':
    url = 'https://webapi.sporttery.cn/gateway/lottery/getHistoryPageListV1.qry?gameNo=85&provinceId=0&pageSize=1&isVerify=0&pageNo=1'  # 替换为实际的大乐透中奖号码公布页面URL
    numbers = fetch_lotto_numbers(url)
    # if numbers:
    #     print("大乐透中奖号码：", numbers)
    # else:
    #     print("未能抓取到中奖号码。")